package com.heima.appgateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order
public class AppGatewayFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断用户是否是登录请求
        String path = request.getURI().getPath();
        if (path.contains("login/login_auth")) {
            return chain.filter(exchange);
        }

        //判断是否有token
        String token = request.getHeaders().getFirst("token");
        if (token == null) {
            response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
            return response.setComplete();
        }
        //解析token的数据部分
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        //判断token是否合法  -1：有效，0：有效，1：过期，2：过期
        if (i == -1 || i == 0) {
            String id = claimsBody.get("id") + "";
            ServerHttpRequest resultRequest = request.mutate().header("userId", id).build();
            ServerWebExchange resultExchange = exchange.mutate().request(resultRequest).build();
            return  chain.filter(resultExchange);
        }
        response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        return response.setComplete();
    }


}
